// 阿里云直播SDK
import Aliplayer from 'aliyun-aliplayer'
import 'aliyun-aliplayer/build/skins/default/aliplayer-min.css'
import { AliRTSPusher, type RtsClient } from 'aliyun-rts-pusher'
class customAliLiveSDK implements UTILS.AliLiveSDK {
  constructor() {
    console.log('中源来 AliLiveSDK installed')
  }
  pushClient: RtsClient | null = null
  /**
   * 拉流初始化
   * @param id 拉流容器id
   * @param pullUrl 拉流一级地址
   * @param pullUrlFlv 拉流二级地址flv
   */
  public initPullStream(id: string, pullUrl: string, pullUrlFlv: string) {
    const player = new Aliplayer(
      {
        id,
        license: {
          domain: 'zhongyuanlai.cn',
          key: 'GPrPEB9e94JukFFit1ba6ad0c86364f779d4008d58dd9220e',
        },
        source: pullUrl,
        isLive: true,
        rtsFallbackSource: pullUrlFlv,
        width: '100%',
        height: '100%',
        autoplay: true,
        playsinline: true,
        skipRtsSupportCheck: false,
      },
      function (player: any) {
        console.log('播放器初始化完成')
      },
    )
    player.on('rtsFallback', function (event: any) {
      if (event.paramData.reason.error_code === 4004) {
        window.$message.warning('直播暂未开启')
        player.dispose()
      }
      console.log('降级的原因', event.paramData.reason)
      console.log('降级到的地址', event.paramData.fallbackUrl)
    })
    player.on('rtsTraceId', function (event: any) {
      console.log('拉流成功', event.paramData)
    })
    player.on('volumechange', function (event: any) {
      console.log('Volume changed to:', event.paramData.volume)
    })
  }
  /**
   * 推流初始化
   * @param id 推流容器id
   */
  public async pushStreamInit(id: string) {
    this.pushClient = AliRTSPusher.createClient()
    const videoEl = this.pushClient.setRenderView(id)
    videoEl!.muted = true
    await this.pushClient.startMicrophone()
    await this.pushClient.startCamera()
    this.pushClient.on('error', (err: any) => {
      console.log('推流错误,错误码：', err.errorCode)
    })
  }
  //停止直播推流
  public stopPushStream() {
    this.pushClient?.stopPush()
  }
}
export default new customAliLiveSDK()
